﻿using System.Reflection;
using Pansoft.HIME.Base.Interfaces;

namespace Pansoft.HIME.Base.Abstracts
{
    /// <summary>本抽象类描述的是一些较简单的显示实体，规则：该显示实体的的属性和源实体的命名一样
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class SimpleViewModel<T> : IViewModel<T> where T : class, new()
    {
        #region Implementation of IViewModel<T>

        /// <summary>将指定的对象成当前的ViewModel对象
        /// </summary>
        /// <param name="entity">指定的对象</param>
        public virtual void Translate(T entity)
        {
            PropertyInfo[] vm = GetType().GetProperties();
            PropertyInfo[] et = entity.GetType().GetProperties();
            foreach (PropertyInfo vmPropertyInfo in vm)
            {
                foreach (PropertyInfo etPropertyInfo in et)
                {
                    if (Compare(vmPropertyInfo, etPropertyInfo))
                        vmPropertyInfo.SetValue(this, etPropertyInfo.GetValue(entity, null), null);
                }
            }
        }

        /// <summary>当转换成比较两个实体的属性是否相同
        /// </summary>
        protected virtual bool Compare(PropertyInfo vmPi, PropertyInfo entityPi)
        {
            return vmPi.Name == entityPi.Name;
        }

        #endregion
    }
}